
//------------------------------------------------------------------
#property copyright "www.forex-station.cm"
#property link      "www.forex-station.cm"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_minimum 0
#property indicator_maximum 1
#property strict

//
//
//
//
//

enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_tbiased2,   // Trend biased (extreme) price
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased,  // Heiken ashi trend biased price
   pr_hatbiased2, // Heiken ashi trend biased (extreme) price
   pr_habclose,   // Heiken ashi (better formula) close
   pr_habopen ,   // Heiken ashi (better formula) open
   pr_habhigh,    // Heiken ashi (better formula) high
   pr_hablow,     // Heiken ashi (better formula) low
   pr_habmedian,  // Heiken ashi (better formula) median
   pr_habtypical, // Heiken ashi (better formula) typical
   pr_habweighted,// Heiken ashi (better formula) weighted
   pr_habaverage, // Heiken ashi (better formula) average
   pr_habmedianb, // Heiken ashi (better formula) median body
   pr_habtbiased, // Heiken ashi (better formula) trend biased price
   pr_habtbiased2 // Heiken ashi (better formula) trend biased (extreme) price
};
enum enFilterType
{
   flt_val, // Apply filter to jurik value
   flt_prc, // Apply filter to price
   flt_all  // Apply filter to all
};

extern ENUM_TIMEFRAMES   TimeFrame       = PERIOD_CURRENT;   // Time frame
input int                Length          = 15;               // Jurik and filter period to use
input double             Phase           = 0.0;              // Jurik phase 
input bool               Double          = false;            // Jurik smooth double
input enPrices           Price           = pr_haweighted;    // Price to use
input double             Filter          = 0;                // Filter to use for filtering (<=0 for no filtering)
input enFilterType       FilterType      = flt_all;          // Filter should be applied to :
input int                Shift           = 0;                // JMA shift
input int                HistoWidth      = 3;                // Histogram bars width
input color              UpHistoColor    = clrLimeGreen;     // Bullish jurik filter color
input color              DnHistoColor    = clrRed;           // Bearish jurik filter color


double jur[],jurDa[],jurDb[],trend[],count[];
string indicatorFileName;
#define _mtfCall(_buff,_ind) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Length,Phase,Double,Price,Filter,FilterType,0,HistoWidth,UpHistoColor,DnHistoColor,_buff,_ind)

//+------------------------------------------------------------------
//|                                                                 |
//+------------------------------------------------------------------
//
//

int OnInit()
{
   IndicatorBuffers(5);
   SetIndexBuffer(0,jurDa,INDICATOR_DATA); SetIndexStyle(0,DRAW_HISTOGRAM,EMPTY,HistoWidth,UpHistoColor);
   SetIndexBuffer(1,jurDb,INDICATOR_DATA); SetIndexStyle(1,DRAW_HISTOGRAM,EMPTY,HistoWidth,DnHistoColor); 
   SetIndexBuffer(2,jur); 
   SetIndexBuffer(3,trend);
   SetIndexBuffer(4,count);
   
   indicatorFileName = WindowExpertName();
   TimeFrame         = fmax(TimeFrame,_Period);
   
   for (int i=0; i<7; i++) SetIndexShift(i,Shift*TimeFrame/_Period);
   
   IndicatorSetString(INDICATOR_SHORTNAME,timeFrameToString(TimeFrame)+" Jurik filter histo("+(string)Length+")");
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason) {  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime& time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   int i=rates_total-prev_calculated+1; if (i>=rates_total) i=rates_total-1;  count[0] = i;
      if (TimeFrame != _Period)
      {
         i = (int)fmax(i,fmin(rates_total-1,_mtfCall(10,0)*TimeFrame/_Period));
            for (; i>=0 && !_StopFlag; i--)
            {
                int y = iBarShift(NULL,TimeFrame,time[i]);
                   jurDa[i]  = _mtfCall(0,y);
                   jurDb[i]  = _mtfCall(1,y);                          
            }
   return(rates_total);
   }
     
   //
   //
   //
   //
   //

   double pfilter = Filter; if (FilterType==flt_val) pfilter=0;
   double vfilter = Filter; if (FilterType==flt_prc) vfilter=0;
   for (; i>=0 && !_StopFlag; i--)
   {
       double price = iFilter(getPrice(Price,open,close,high,low,i,rates_total),pfilter,Length,i,rates_total,0);
       jur[i]   =     iFilter(iDSmooth(price,Length,Phase,Double,i,rates_total),vfilter,Length,i,rates_total,1);
       trend[i] = (i<rates_total-1) ? (jur[i]>jur[i+1]) ? 1 : (jur[i]<jur[i+1]) ? -1 : trend[i+1] : 0;  
       jurDa[i] = (trend[i] == 1) ? 1 : EMPTY_VALUE;
       jurDb[i] = (trend[i] ==-1) ? 1 : EMPTY_VALUE;      
   }
return(rates_total);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

#define _smoothInstances     1
#define _smoothInstancesSize 20
double _smthWork[][_smoothInstances*_smoothInstancesSize];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

double iDSmooth(double price, double length, double phase, bool isDouble, int i, int bars, int inNo=0) 
{
   inNo*=_smoothInstancesSize;
   if (isDouble)
         return (iSmooth(iSmooth(price,sqrt(length),phase,i,bars,inNo),sqrt(length),phase,i,bars,inNo+10));
   else  return (iSmooth(price,length,phase,i,bars,inNo));
}

//
//
//
//
//

double iSmooth(double price, double length, double phase, int r, int bars, int instanceNo=0)
{
   if (ArrayRange(_smthWork,0)!=bars) ArrayResize(_smthWork,bars);  r = bars-r-1;
   if (price==EMPTY_VALUE) price=0;

   if (r==0 || length<=1){ int k=0; for(; k<volty; k++) _smthWork[0][instanceNo+k]=price; for(; k<instanceNo; k++) _smthWork[0][instanceNo+k]=0; return(price); }

      //
      //
      //
      //
      //
  
      double len1   = fmax(log(sqrt(0.5*(length-1)))/log(2.0)+2.0,0);
      double pow1   = fmax(len1-2.0,0.5);
      double del1   = price - _smthWork[r-1][instanceNo+bsmax],absDel1 = fabs(del1);
      double del2   = price - _smthWork[r-1][instanceNo+bsmin],absDel2 = fabs(del2);
      int    forBar = (int)fmin(r,10);
      
         _smthWork[r][instanceNo+volty]  = (absDel1 > absDel2) ? absDel1 : (absDel1 < absDel2) ? absDel2 : 0;
         _smthWork[r][instanceNo+vsum]   = _smthWork[r-1][instanceNo+vsum] + (_smthWork[r][instanceNo+volty]-_smthWork[r-forBar][instanceNo+volty])*0.1;
         _smthWork[r][instanceNo+avolty] = _smthWork[r-1][instanceNo+avolty]+(2.0/(fmax(4.0*length,30)+1.0))*(_smthWork[r][instanceNo+vsum]-_smthWork[r-1][instanceNo+avolty]);
        
         //
         //
         //
         //
         //
              
         double dVolty    = (_smthWork[r][instanceNo+avolty]>0) ? _smthWork[r][instanceNo+volty]/_smthWork[r][instanceNo+avolty] : 0;  
         double dVoltyTmp = pow(len1,1.0/pow1);
         if (dVolty > dVoltyTmp) dVolty = dVoltyTmp;
         if (dVolty < 1.0)       dVolty = 1.0;
         
         //
         //
         //
         //
         //
        
         double pow2 = pow(dVolty, pow1);
         double len2 = sqrt(0.5*(length-1))*len1;
         double Kv   = pow(len2/(len2+1),sqrt(pow2));

            _smthWork[r][instanceNo+bsmax] = (del1>0) ? price : price - Kv*del1;
            _smthWork[r][instanceNo+bsmin] = (del2<0) ? price : price - Kv*del2;
             
      //
      //
      //
      //
      //
      
      double corr  = fmax(fmin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = pow(beta,pow2);

         _smthWork[r][instanceNo+0] = price + alpha*(_smthWork[r-1][instanceNo+0]-price);
         _smthWork[r][instanceNo+1] = (price - _smthWork[r][instanceNo+0])*(1-beta) + beta*_smthWork[r-1][instanceNo+1];
         _smthWork[r][instanceNo+2] = (_smthWork[r][instanceNo+0]   + corr*_smthWork[r][instanceNo+1]);
         _smthWork[r][instanceNo+3] = (_smthWork[r][instanceNo+2]   - _smthWork[r-1][instanceNo+4])*((1-alpha)*(1-alpha)) + (alpha*alpha)*_smthWork[r-1][instanceNo+3];
         _smthWork[r][instanceNo+4] = (_smthWork[r-1][instanceNo+4] + _smthWork[r][instanceNo+3]);
return(_smthWork[r][instanceNo+4]);
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

#define _filterInstances     2
#define _filterInstancesSize 3
double workFil[][_filterInstances*_filterInstancesSize];

#define _fchange 0
#define _fachang 1
#define _fprice  2

double iFilter(double tprice, double filter, int period, int i, int bars, int instanceNo=0)
{
   if (filter<=0) return(tprice);
   if (ArrayRange(workFil,0)!= bars) ArrayResize(workFil,bars); i = #ifdef __MQL4__ bars-i-1 #else i #endif; instanceNo*=_filterInstancesSize;
   
   //
   //
   //
   //
   //
   
   workFil[i][instanceNo+_fprice]  = tprice; if (i<1) return(tprice);
   workFil[i][instanceNo+_fchange] = MathAbs(workFil[i][instanceNo+_fprice]-workFil[i-1][instanceNo+_fprice]);
   workFil[i][instanceNo+_fachang] = workFil[i][instanceNo+_fchange];

   for (int k=1; k<period && (i-k)>=0; k++) workFil[i][instanceNo+_fachang] += workFil[i-k][instanceNo+_fchange];
                                            workFil[i][instanceNo+_fachang] /= period;
    
   double stddev = 0; for (int k=0;  k<period && (i-k)>=0; k++) stddev += MathPow(workFil[i-k][instanceNo+_fchange]-workFil[i-k][instanceNo+_fachang],2);
          stddev = MathSqrt(stddev/(double)period); 
   double filtev = filter * stddev;
   if( MathAbs(workFil[i][instanceNo+_fprice]-workFil[i-1][instanceNo+_fprice]) < filtev ) workFil[i][instanceNo+_fprice]=workFil[i-1][instanceNo+_fprice];
        return(workFil[i][instanceNo+_fprice]);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     1
#define _priceInstancesSize 4
double workHa[][_priceInstances*_priceInstancesSize];
double getPrice(int tprice, const double& open[], const double& close[], const double& high[], const double& low[], int i, int bars, int instanceNo=0)
{
  if (tprice>=pr_haclose)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars); instanceNo*=_priceInstancesSize; int r = bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen  = (r>0) ? (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0 : (open[i]+close[i])/2;;
         double haClose = (open[i]+high[i]+low[i]+close[i]) / 4.0;
         if (_prHABF(tprice))
               if (high[i]!=low[i])
                     haClose = (open[i]+close[i])/2.0+(((close[i]-open[i])/(high[i]-low[i]))*MathAbs((close[i]-open[i])/2.0));
               else  haClose = (open[i]+close[i])/2.0; 
         double haHigh  = fmax(high[i], fmax(haOpen,haClose));
         double haLow   = fmin(low[i] , fmin(haOpen,haClose));

         //
         //
         //
         //
         //
         
         if(haOpen<haClose) { workHa[r][instanceNo+0] = haLow;  workHa[r][instanceNo+1] = haHigh; } 
         else               { workHa[r][instanceNo+0] = haHigh; workHa[r][instanceNo+1] = haLow;  } 
                              workHa[r][instanceNo+2] = haOpen;
                              workHa[r][instanceNo+3] = haClose;
         //
         //
         //
         //
         //
         
         switch (tprice)
         {
            case pr_haclose:
            case pr_habclose:    return(haClose);
            case pr_haopen:   
            case pr_habopen:     return(haOpen);
            case pr_hahigh: 
            case pr_habhigh:     return(haHigh);
            case pr_halow:    
            case pr_hablow:      return(haLow);
            case pr_hamedian:
            case pr_habmedian:   return((haHigh+haLow)/2.0);
            case pr_hamedianb:
            case pr_habmedianb:  return((haOpen+haClose)/2.0);
            case pr_hatypical:
            case pr_habtypical:  return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:
            case pr_habweighted: return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:  
            case pr_habaverage:  return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
            case pr_habtbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
            case pr_hatbiased2:
            case pr_habtbiased2:
               if (haClose>haOpen)  return(haHigh);
               if (haClose<haOpen)  return(haLow);
                                    return(haClose);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (tprice)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_medianb:   return((open[i]+close[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case pr_tbiased:   
               if (close[i]>open[i])
                     return((high[i]+close[i])/2.0);
               else  return((low[i]+close[i])/2.0);        
      case pr_tbiased2:   
               if (close[i]>open[i]) return(high[i]);
               if (close[i]<open[i]) return(low[i]);
                                     return(close[i]);        
   }
   return(0);
}

//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

bool checkName()
{
   static bool checkedOnStart = false; if (checkedOnStart) return(true);
   string en = WindowExpertName(); StringToLower(en);
   string or = "jurik filter histo";
   bool   error = (en!=or);
      if (!error) error = (StringFind(MQLInfoString(MQL_PROGRAM_PATH),"::",0)>0);

   //
   //
   //
   //
   //
         
   if (error)
   {
      Alert("contact forex station");
      Alert("You are trying to use renamed indicator");
      return(false);
   }         
   checkedOnStart = true;
   return(true);
}


